package com.bree.erp.service.stateless;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.User;
import com.bree.erp.service.UserService;
import com.bree.erp.service.util.ServiceUtil;

@Stateless
public class UserServiceBean implements UserService {

	@PersistenceContext()
	private EntityManager em;

	public UserServiceBean() {

	}

	public UserServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public User create(String email, String password, String firstName,
			String lastName) {

		User user = new User();

		user.setEmail(email);
		if (password != null) {
			user.setPassword(ServiceUtil.encodePassword(password));
		} else {
			user.setPassword("");
		}

		user.setFirstName(firstName);
		user.setLastName(lastName);

		em.persist(user);

		return user;
	}
	
	@Override
	public User read(String email) {
		return em.find(User.class, email);
	}

	@Override
	public Collection<User> list() {

		TypedQuery<User> query = em.createQuery("SELECT p FROM User p",
				User.class);
		return query.getResultList();
	}

	@Override
	public void delete(User user) {

		em.remove(user);
	}

	@Override
	public void update(String email, String firstname, String lastname) {
		
		User user = read(email);
		
		user.setFirstName(firstname);
		user.setLastName(lastname);
		
	}

	@Override
	public void updatePassword(String email, String newPassword) {
		
		User user = read(email);
		user.setPassword(ServiceUtil.encodePassword(newPassword));
	}

}
